package cn.melonlib.cores.jpa.model.bean.impl;

import cn.melonlib.cores.commons.comp.enums.OrderByType;
import cn.melonlib.cores.commons.comp.enums.QueryType;
import cn.melonlib.cores.commons.model.entity.IEntity;
import cn.melonlib.cores.jpa.model.bean.Query;
import cn.melonlib.objects.maps.JsonMap;
import lombok.Getter;
import org.intellij.lang.annotations.Language;
import org.springframework.core.annotation.AnnotationUtils;

import javax.persistence.Entity;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

@Getter
public class DefaultQuery implements Query {

    private final String content;

    private final List<? extends Serializable> params;

    private final QueryType queryType;

    private Class<? extends IEntity> entityClass;

    private JsonMap<JsonMap<Object>> filter;

    private JsonMap<OrderByType> orderBy;

    public DefaultQuery(@Language("HQL") String content,List<? extends Serializable> params ){
        this(content,params,JsonMap.<OrderByType>createMap().append("id",OrderByType.ASC) ,QueryType.HIBERNATE_QL);
    }
    public DefaultQuery(@Language("HQL") String content, List<? extends Serializable> params , JsonMap<OrderByType> orderBy){
        this(content,params,orderBy,QueryType.HIBERNATE_QL);
    }



    public DefaultQuery(@Language("HQL") String content, List<? extends Serializable> params, JsonMap<OrderByType> orderBy , QueryType queryType){
        this.content=content;
        this.params=params;
        this.queryType=queryType;
        this.orderBy=orderBy;
    }

    public DefaultQuery(Class<? extends IEntity> entityType, JsonMap<JsonMap<Object>> filter, JsonMap<OrderByType> orderBy){
        Entity entity=AnnotationUtils.findAnnotation(entityType, Entity.class);
        this.content= entity==null?entityType.getSimpleName():entity.name();
        this.queryType=QueryType.JPA;
        this.params= Collections.emptyList();
        this.entityClass=entityType;
        this.filter=filter;
        this.orderBy=orderBy;
    }
    public DefaultQuery(Class<? extends IEntity> entityType, JsonMap<JsonMap<Object>> filter){

        this(entityType,filter, JsonMap.<OrderByType>createMap().append("id",OrderByType.ASC));

    }



    public int length() {
        return this.content.length();
    }

    @Override
    public char charAt(int index) {
        return this.content.charAt(index);
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return this.content.subSequence(start,end);
    }

    @Override
    public String toString() {
        return this.content;
    }

    

}
